﻿using System.Web.Mvc;
using System.Text;
using System.Web;
using System;

namespace NETMovie.UI.WebMVC.Helpers
{
    public static class SiteMapViewHelper
    {
        private static void AppendChildren(StringBuilder sb, SiteMapNode root, Func<SiteMapNode, string> itemContent)
        {
            var children = root.ChildNodes;

            if (children.Count == 0)
            {
                sb.Append("</li>");
                return;
            }

            sb.AppendLine("\r\n<ul>");
            foreach (SiteMapNode item in children)
            {
                RenderLi(sb, item, itemContent);
                AppendChildren(sb, item, itemContent);
            }

            sb.AppendLine("</ul></li>");
        }

        private static void RenderLi(StringBuilder sb, SiteMapNode item, Func<SiteMapNode, string> itemContent)
        {
            sb.AppendFormat("<li>{0}", itemContent(item));
        }

        public static string SiteMapView(this HtmlHelper html, string treeId)
        {
            return html.SiteMapView(treeId, m => m.Title);
        }

        public static string SiteMapView(this HtmlHelper html, string treeId, Func<SiteMapNode, string> itemContent)
        {
            var nodes = SiteMap.RootNode.ChildNodes;
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("<ul id='{0}'>\r\n", treeId);

            foreach (SiteMapNode item in nodes)
            {
                RenderLi(sb, item, itemContent);
                AppendChildren(sb, item, itemContent);
            }

            sb.AppendLine("</ul>");

            return sb.ToString();
        }
    }
}